import React, { Component } from 'react';
import { progressConfig } from '../config';
import styles from './index.less';

const {
  defaultFrontColorWithBg,
  defaultFrontColor,
  defaultBackgroundColor,
  defaultStrokeWidth,
} = progressConfig;

class MiniProgress extends Component {
  state = {
    viewportScale: window.viewportScale,
  };

  componentDidMount() {
    window.addEventListener('resize', this.resize, { passive: true });
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize);
  }

  resize = () => {
    this.setState({ viewportScale: window.viewportScale });
  };

  render() {
    const { viewportScale } = this.state;
    const {
      style,
      color,
      backgroundColor = defaultBackgroundColor,
      strokeWidth = defaultStrokeWidth,
      percent = 0,
      hiddenBg,
      showValue,
      value,
    } = this.props;
    const frontColor = color || (hiddenBg ? defaultFrontColor : defaultFrontColorWithBg);
    return (
      <div className={`${styles.miniProgress} ${showValue ? styles.flexBox : ''}`} style={style}>
        <div className={showValue ? styles.flexInner : ''}>
          <div
            className={styles.progressWrap}
            style={{
              background: hiddenBg ? 'rgba(0,0,0,0)' : backgroundColor,
              borderRadius: hiddenBg ? 0 : (strokeWidth * viewportScale) / 2,
            }}
          >
            <div
              className={styles.progress}
              style={{
                background: frontColor,
                width: percent ? `${percent > 100 ? 100 : percent}%` : null,
                height: strokeWidth * viewportScale,
                borderRadius: hiddenBg ? 0 : (strokeWidth * viewportScale) / 2,
              }}
            />
          </div>
        </div>
        {showValue && <div style={{ width: '1.3rem' }}>{value || `${percent}%`}</div>}
      </div>
    );
  }
}

export default MiniProgress;
